package com.zahb.qadx.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.model.ArchivesBean;
import com.zahb.qadx.model.NationBean;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.ui.view.CircleImageView;
import com.zahb.qadx.ui.view.ClearEditText;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.GlideImageLoader;
import com.zahb.qadx.util.ImageLoaderKt;
import com.zahb.qadx.util.RegularUtil;
import com.zahb.qadx.util.Tips;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;


public class EditInfoActivity extends BaseActivity {
    @BindView(R.id.tvSave)
    TextView tvSave;
    @BindView(R.id.ivHead)
    CircleImageView ivHead;
    @BindView(R.id.etName)
    ClearEditText etName;
    @BindView(R.id.etPhone)
    ClearEditText etPhone;
    @BindView(R.id.etIdcard)
    ClearEditText etIdcard;
    @BindView(R.id.tvSex)
    TextView tvSex;
    @BindView(R.id.tvNation)
    TextView tvNation;
    @BindView(R.id.tvBirth)
    TextView tvBirth;
    @BindView(R.id.etCompany)
    ClearEditText etCompany;
    @BindView(R.id.etPost)
    ClearEditText etPost;
    @BindView(R.id.etTitle)
    ClearEditText etTitle;
    @BindView(R.id.tvEducation)
    TextView tvEducation;
    @BindView(R.id.tvPolitical)
    TextView tvPolitical;
    @BindView(R.id.rlSex)
    RelativeLayout rlSex;
    @BindView(R.id.rlNation)
    RelativeLayout rlNation;
    @BindView(R.id.rlBirthday)
    RelativeLayout rlBirthday;
    @BindView(R.id.rlEducation)
    RelativeLayout rlEducation;
    @BindView(R.id.rlPolitical)
    RelativeLayout rlPolitical;


    int sex=-1;

    int nation=-1;
    NationBean nationBean;

    private TimePickerView mTermStartPicker;
    private SimpleDateFormat mDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);

    String birth="";

    int education = -1;

    int political = -1;

    OptionsPickerView optionsPickerView;

    @Override
    protected int getLayout() {
        return R.layout.activity_edit_info;
    }

    @Override
    protected void initViews() {

        mUnbinder = ButterKnife.bind(this);

        Gson gson = new Gson();
        nationBean = gson.fromJson(getResources().getString(R.string.nation), NationBean.class);


        String name = getIntent().getStringExtra("name");
        String phone = getIntent().getStringExtra("phone");



        if(!TextUtils.isEmpty(name)){
            etName.setText(name);
            etName.setEnabled(false);
            etName.setClickable(false);
            etName.invisibleClear = true;
        }
        if(!TextUtils.isEmpty(phone)){
            etPhone.setText(phone);
            etPhone.setEnabled(false);
            etPhone.setClickable(false);
            etPhone.invisibleClear = true;
        }

        if(MyArchivesActivity.archive!=null){
            if(MyArchivesActivity.archive.getInfoVO()!=null){
                ArchivesBean.InfoVOEntity infoVOEntity = MyArchivesActivity.archive.getInfoVO();
                if(!isEmpty(infoVOEntity.getBirthday())){
                    tvBirth.setTextColor(getResources().getColor(R.color.tv));
                    tvBirth.setText(infoVOEntity.getBirthday());
                    birth = infoVOEntity.getBirthday();
                }
                if(!isEmpty(infoVOEntity.getEducation())){
                    int edu = Integer.parseInt(infoVOEntity.getEducation());
                    if(edu>0){
                        List<String> list = new ArrayList<>();
                        list.add("小学");
                        list.add("初中");
                        list.add("高中");
                        list.add("技工学校");
                        list.add("中专或中技");
                        list.add("专科");
                        list.add("本科");
                        list.add("研究生");
                        list.add("其它");
                        tvEducation.setTextColor(getResources().getColor(R.color.tv));
                        tvEducation.setText(list.get(edu-1));
                        education = edu;
                    }
                }
                if(!isEmpty(infoVOEntity.getHeadImg())){
                    ImageLoaderKt.loadImageCircle(ivHead, infoVOEntity.getHeadImg());
                    imgUrl = infoVOEntity.getHeadImg();
                }
                if(!isEmpty(infoVOEntity.getGender())){
                    int g = Integer.parseInt(infoVOEntity.getGender());
                    if(g>0){
                        List<String> list = new ArrayList<>();
                        list.add("男");
                        list.add("女");

                        tvSex.setTextColor(getResources().getColor(R.color.tv));
                        tvSex.setText(list.get(g-1));
                        sex = g;
                    }
                }
                if(!isEmpty(infoVOEntity.getNation())){
                    int n = Integer.parseInt(infoVOEntity.getNation());
                    if(n>0){
                        List<String> list = new ArrayList<>();
                        for (NationBean.NationEntity nationEntity : nationBean.getNation()){
                            list.add(nationEntity.getText());
                        }
                        tvNation.setTextColor(getResources().getColor(R.color.tv));
                        tvNation.setText(list.get(n-1));
                        nation = n;
                    }
                }
                if(!isEmpty(infoVOEntity.getIdCard())){
                    etIdcard.setText(infoVOEntity.getIdCard());
                }
                if(!isEmpty(infoVOEntity.getJob())){
                    etPost.setText(infoVOEntity.getJob());
                }
                if(!isEmpty(infoVOEntity.getPhone())){
                    etPhone.setText(infoVOEntity.getPhone());
                }
                if(!isEmpty(infoVOEntity.getName())){
                    etName.setText(infoVOEntity.getName());
                }

                if(!isEmpty(infoVOEntity.getCompany())){
                    etCompany.setText(infoVOEntity.getCompany());
                }
                if(!isEmpty(infoVOEntity.getPoliticalOutlook())){
                    int p = Integer.parseInt(infoVOEntity.getPoliticalOutlook());
                    if(p>0){
                        List<String> list = new ArrayList<>();


                        list.add("中共党员");
                        list.add("中共预备党员");
                        list.add("共青团员");
                        list.add("民革党员");
                        list.add("民盟盟员");
                        list.add("民建会员");
                        list.add("民进会员");
                        list.add("农工党党员");
                        list.add("致公党党员");
                        list.add("九三学社社员");
                        list.add("台盟盟员");
                        list.add("无党派人士");
                        list.add("群众");

                        tvPolitical.setTextColor(getResources().getColor(R.color.tv));
                        tvPolitical.setText(list.get(p-1));
                        political = p;
                    }
                }

                if(!isEmpty(infoVOEntity.getProfessional())){
                    etTitle.setText(infoVOEntity.getProfessional());
                }
            }
        }


        ivHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //相册
                PictureSelector.create(EditInfoActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .imageEngine(GlideImageLoader.createGlideEngine())
                        .isEnableCrop(true)
                        .cropImageWideHigh(295,413)
                        .isCompress(true)
                        .compressQuality(40) // 图片压缩后输出质量
                        .maxSelectNum(1)
                        .minSelectNum(1)
                        .imageSpanCount(4)
                        .selectionMode(PictureConfig.SINGLE)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }
        });


        rlSex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<String> list = new ArrayList<>();
                list.add("男");
                list.add("女");

                optionsPickerView =new OptionsPickerBuilder(EditInfoActivity.this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int position, int options2, int options3, View v) {
                        sex = position+1;
                        tvSex.setText(list.get(position));
                        tvSex.setTextColor(getResources().getColor(R.color.tv));
                    }
                }).setTitleText("请选择性别")
                        .setLayoutRes(R.layout.pickerview_custom_options,
                                new CustomListener() {
                                    @Override
                                    public void customLayout(View v) {
                                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                                        TextView tvCancel = (TextView) v.findViewById(R.id.tv_cancel);
                                        TextView tvTitle = (TextView) v.findViewById(R.id.tvTitle);
                                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                optionsPickerView.returnData();
                                                optionsPickerView.dismiss();
                                            }
                                        });
                                        tvCancel.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                optionsPickerView.dismiss();
                                            }
                                        });
                                        tvTitle.setText("请选择性别");
                                    }
                                })
                        .build();
                optionsPickerView.setPicker(list);
                optionsPickerView.show();

            }
        });




        rlNation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                List<String> list = new ArrayList<>();
                for (NationBean.NationEntity nationEntity : nationBean.getNation()){
                    list.add(nationEntity.getText());
                }
/*                LinearLayoutManager layoutManager = new LinearLayoutManager(EditInfoActivity.this);
                new  CircleDialog.Builder()
                        .setTitle("请选择民族")
                        .setItems(list,layoutManager,new OnRvItemClickListener(){
                            @Override
                            public boolean onItemClick(View view, int position) {
                                nation = nationBean.getNation().get(position).getValue();
                                tvNation.setText(list.get(position));
                                tvNation.setTextColor(getResources().getColor(R.color.tv));
                                return true;
                            }
                        })
                        .show(getSupportFragmentManager());*/


                optionsPickerView =new OptionsPickerBuilder(EditInfoActivity.this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int position, int options2, int options3, View v) {
                        nation = nationBean.getNation().get(position).getValue();
                        tvNation.setText(list.get(position));
                        tvNation.setTextColor(getResources().getColor(R.color.tv));
                    }
                }).setTitleText("请选择民族")
                        .setLayoutRes(R.layout.pickerview_custom_options,
                                new CustomListener() {
                                    @Override
                                    public void customLayout(View v) {
                                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                                        TextView tvCancel = (TextView) v.findViewById(R.id.tv_cancel);
                                        TextView tvTitle = (TextView) v.findViewById(R.id.tvTitle);
                                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                optionsPickerView.returnData();
                                                optionsPickerView.dismiss();
                                            }
                                        });
                                        tvCancel.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                optionsPickerView.dismiss();
                                            }
                                        });
                                        tvTitle.setText("请选择民族");
                                    }
                                })
                        .build();
                optionsPickerView.setPicker(list);
                optionsPickerView.show();
            }
        });

        Calendar startD = Calendar.getInstance();
        startD.set(1949,10,1);
        Calendar endD = Calendar.getInstance();
        rlBirthday.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mTermStartPicker == null) {
                    mTermStartPicker = new TimePickerBuilder(getContext(), (date, v2) -> {
                        birth = mDateTimeFormat.format(date);
                        tvBirth.setText(mDateTimeFormat.format(date));
                        tvBirth.setTextColor(getResources().getColor(R.color.tv));
                    }).setType(new boolean[]{true, true, true, false, false, false})
                            .setTitleText("请选择出生年月")
                            .setDate(endD)
                            .setRangDate(startD,endD)
                            .setLayoutRes(R.layout.pickerview_custom_time,
                                    new CustomListener() {
                                        @Override
                                        public void customLayout(View v) {
                                            final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                                            TextView tvCancel = (TextView) v.findViewById(R.id.tv_cancel);
                                            TextView tvNow = (TextView) v.findViewById(R.id.tvNow);
                                            TextView tvTitle = (TextView) v.findViewById(R.id.tvTitle);
                                            tvSubmit.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    mTermStartPicker.returnData();
                                                    mTermStartPicker.dismiss();
                                                }
                                            });
                                            tvCancel.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    mTermStartPicker.dismiss();
                                                }
                                            });
                                            tvNow.setVisibility(View.INVISIBLE);
                                            tvTitle.setText("请选择出生年月");
                                        }
                                    })
                            .build();
                }
                mTermStartPicker.show();
            }
        });

        rlEducation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<String> list = new ArrayList<>();

                list.add("小学");
                list.add("初中");
                list.add("高中");
                list.add("技工学校");
                list.add("中专或中技");
                list.add("专科");
                list.add("本科");
                list.add("研究生");
                list.add("其它");




                 optionsPickerView =new OptionsPickerBuilder(EditInfoActivity.this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int position, int options2, int options3, View v) {
                        education = position+1;
                        tvEducation.setText(list.get(position));
                        tvEducation.setTextColor(getResources().getColor(R.color.tv));
                    }
                }).setTitleText("请选择学历")
                        .setLayoutRes(R.layout.pickerview_custom_options,
                                new CustomListener() {
                                    @Override
                                    public void customLayout(View v) {
                                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                                        TextView tvCancel = (TextView) v.findViewById(R.id.tv_cancel);
                                        TextView tvTitle = (TextView) v.findViewById(R.id.tvTitle);
                                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                optionsPickerView.returnData();
                                                optionsPickerView.dismiss();
                                            }
                                        });
                                        tvCancel.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                optionsPickerView.dismiss();
                                            }
                                        });
                                        tvTitle.setText("请选择学历");
                                    }
                                })
                        .build();
                optionsPickerView.setPicker(list);
                optionsPickerView.show();
            }
        });

        rlPolitical.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<String> list = new ArrayList<>();


                list.add("中共党员");
                list.add("中共预备党员");
                list.add("共青团员");
                list.add("民革党员");
                list.add("民盟盟员");
                list.add("民建会员");
                list.add("民进会员");
                list.add("农工党党员");
                list.add("致公党党员");
                list.add("九三学社社员");
                list.add("台盟盟员");
                list.add("无党派人士");
                list.add("群众");




                optionsPickerView =new OptionsPickerBuilder(EditInfoActivity.this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int position, int options2, int options3, View v) {
                        political = position+1;
                        tvPolitical.setText(list.get(position));
                        tvPolitical.setTextColor(getResources().getColor(R.color.tv));
                    }
                }).setTitleText("请选择政治面貌")
                        .setLayoutRes(R.layout.pickerview_custom_options,
                                new CustomListener() {
                                    @Override
                                    public void customLayout(View v) {
                                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                                        TextView tvCancel = (TextView) v.findViewById(R.id.tv_cancel);
                                        TextView tvTitle = (TextView) v.findViewById(R.id.tvTitle);
                                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                optionsPickerView.returnData();
                                                optionsPickerView.dismiss();
                                            }
                                        });
                                        tvCancel.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                optionsPickerView.dismiss();
                                            }
                                        });
                                        tvTitle.setText("请选择政治面貌");
                                    }
                                })
                        .build();
                optionsPickerView.setPicker(list);
                optionsPickerView.show();
            }
        });


        tvSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(TextUtils.isEmpty(imgUrl)){
                    showBindToast("请上传头像");
                    return;
                }
                if(TextUtils.isEmpty(etName.getText().toString())){
                    showBindToast("请输入姓名");
                    return;
                }
                if(TextUtils.isEmpty(etPhone.getText().toString())){
                    showBindToast("请输入手机号");
                    return;
                }

                if(TextUtils.isEmpty(etIdcard.getText().toString())){
                    showBindToast("请输入身份证号");
                    return;
                }else if(!RegularUtil.isValidCid(etIdcard.getText().toString())){
                    showBindToast("请输入正确的身份证号");
                    return;
                }

                if(sex==-1){
                    showBindToast("请选择性别");
                    return;
                }
                if(isReq){
                    return;
                }
                isReq=true;



                Map<String, Object> params = new HashMap<>();
                params.put("name", etName.getText().toString());
                params.put("phone", etPhone.getText().toString());
                params.put("headImg",imgUrl);
                params.put("idCard", etIdcard.getText().toString());
                params.put("gender", sex);

/*                params.put("nation", nation);
                params.put("birthday",birth);
                params.put("company", etCompany.getText().toString());

                params.put("job", etPost.getText().toString());
                params.put("professional", etTitle.getText().toString());
                params.put("education",education);
                params.put("politicalOutlook", political);//不需要校验*/


                if(nation==-1){
                  //  params.put("nation", "");
                }else{
                    params.put("nation", nation);
                }

                if(TextUtils.isEmpty(birth)){
                   // params.put("birthday","");
                }else{
                    params.put("birthday",birth);
                }

                if(TextUtils.isEmpty(etCompany.getText().toString())){
                 //   params.put("company", "");
                }else{
                    params.put("company", etCompany.getText().toString());
                }


                if(TextUtils.isEmpty(etPost.getText().toString())){
                 //   params.put("job", "");
                }else{
                    params.put("job", etPost.getText().toString());
                }


                if(TextUtils.isEmpty(etTitle.getText().toString())){
                  //  params.put("professional", "");
                }else{
                    params.put("professional", etTitle.getText().toString());
                }
                if(education==-1){
                  //  params.put("education","");
                }else{
                    params.put("education",education);
                }
                if(political==-1){
                   // params.put("politicalOutlook", "");//不需要校验
                }else{
                    params.put("politicalOutlook", political);//不需要校验
                }


                Gson mGson = new Gson();
                String json = mGson.toJson(params);

                RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
                addDisposable(RetrofitService.getNetService()
                        .archives_info(body)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(response -> {
                            isReq=false;
                            if (response.getStatusCode() == 200) {
                                Intent intent = new Intent(EditInfoActivity.this, UploadCertificateActivity.class);
                                startActivity(intent);
                                // finish();
                            } else {
                                showBindToast(response.getErrorInfo());
                            }
                        }, throwable -> {
                            throwable.printStackTrace();
                            Tips.RequestError(getActivity());
                        }));
            }
        });

        archives();
    }

    boolean isReq=false;


    public void archives(){
        addDisposable(RetrofitService.getNetService()
                .archives()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == 200) {
                        MyArchivesActivity.archive = response.getData();
                    }else if (response.getStatusCode() != Constant.CODE_OFFLINE) {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));
    }

    @Override
    protected int getTitleStringRes() {
        return R.string.info;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> images =
                        PictureSelector.obtainMultipleResult(data);
                if (images.size() > 0) {
                    String path = GlideImageLoader.getPath(images.get(0));
                    upload(path);

                }
            }

        }
    }

    public String imgUrl = "";
    public void upload(String path) {
        if (TextUtils.isEmpty(path)) {
            Log.v("zzw", "路径为空");
            return;
        }
        File imgFile = new File(path);
        if (!imgFile.exists() || !imgFile.isFile()) {
            Log.v("zzw", "文件不存在");
            return;
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), imgFile);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", imgFile.getName(), requestBody);
        addDisposable(RetrofitService.getNetService()
                .upload(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == 200) {
                        imgUrl=response.getData();
                        ImageLoaderKt.loadImageCircle(ivHead, response.getData());
                    } else {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));
    }


    boolean first = true;
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if(first){
            first=false;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.CAMERA},110);
            }
        }

    }

    public boolean isEmpty(String target){
        if(TextUtils.isEmpty(target)){
            return true;
        }
        if("noDisplay".equals(target)){
            return true;
        }
        return false;
    }
}
